#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    # 分析配置文件中的权限
    from backend.config.constants_v2 import PERMISSION_FEATURE_MAP
    
    config_permissions = []
    print('🔧 配置文件中的权限:')
    print('='*60)
    for module, config in PERMISSION_FEATURE_MAP.items():
        features = config['features']
        print(f'\n📂 {module} ({config["display_name"]}): {len(features)}个权限')
        for feature, info in features.items():
            code = info['permission_code']
            config_permissions.append(code)
            print(f'   {code}')
    
    print(f'\n📊 配置文件权限总数: {len(config_permissions)}')
    
    # 分析数据库中的权限
    from app import create_app
    from backend.models.permission import Permission
    
    app = create_app()
    with app.app_context():
        db_permissions = Permission.query.all()
        print(f'\n🗄️  数据库权限总数: {len(db_permissions)}')
        
        db_codes = [p.code for p in db_permissions]
        
        # 找出差异
        config_only = set(config_permissions) - set(db_codes)
        db_only = set(db_codes) - set(config_permissions)
        common = set(config_permissions) & set(db_codes)
        
        print(f'\n📈 权限对比分析:')
        print(f'   共同权限: {len(common)}个')
        print(f'   仅在配置文件: {len(config_only)}个')
        print(f'   仅在数据库: {len(db_only)}个')
        
        if config_only:
            print(f'\n🔍 仅在配置文件中的权限:')
            for code in sorted(config_only):
                print(f'   {code}')
        
        if db_only:
            print(f'\n🔍 仅在数据库中的权限:')
            for code in sorted(db_only):
                print(f'   {code}')
                
        # 查看数据库中的权限分类
        print(f'\n🗄️  数据库中的权限分类:')
        categories = {}
        for p in db_permissions:
            category = p.code.split(':')[0] if ':' in p.code else 'other'
            if category not in categories:
                categories[category] = []
            categories[category].append(p.code)
        
        for category, codes in sorted(categories.items()):
            print(f'   {category}: {len(codes)}个')

except Exception as e:
    print(f'❌ 错误: {e}')
    import traceback
    traceback.print_exc()
